package com.privatetime.web;

import java.util.List;

import org.apache.struts2.interceptor.validation.SkipValidation;

import com.opensymphony.xwork2.ModelDriven;
import com.opensymphony.xwork2.Preparable;
import com.privatetime.model.Card;
import com.privatetime.model.User;

public class CardAction extends BaseAction implements ModelDriven<Card>, Preparable {

	private static final long serialVersionUID = 1L;

	private Card card = new Card();
	private List<Card> cardList;
	private User cardUser;
	private Integer userId;

	@Override
	public String create() throws Exception {
		logger.info("createCard is " + card);
		cardService.createEntity(card);
		return ActionStateConstants.SUCCESS;
	}

	public List<Card> getCardList() {
		return cardList;
	}

	public User getCardUser() {
		return cardUser;
	}

	public void setCardUser(User cardUser) {
		this.cardUser = cardUser;
	}

	@Override
	@SkipValidation
	public String delete() throws Exception {
		logger.info("CardAction delete() card id is " + card.getId());
		cardService.deleteEntityById(card.getId());
		userId = ((User) getSession().get(SESSION_USER)).getId();
		logger.info("CardAction delete() success!!! userId=" + userId);
		return ActionStateConstants.SUCCESS;
	}

	@Override
	@SkipValidation
	public String list() {
		logger.info(((User) getSession().get(SESSION_USER)).getId()
				+ "Current User id is " + card.getUser().getId());
		cardUser = userService.retrieveEntity(card.getUser().getId());
		logger.info("Card Action list() user is " + cardUser);
		// cardList = cardService.findCardList(card.getUser().getId());
		logger.info("card user id is " + cardUser.getId());
		return ActionStateConstants.SUCCESS;
	}

	@Override
	@SkipValidation
	public String retrieve() {
		logger.info("retrieve card id is " + card.getId());
		card = cardService.retrieveEntity(card.getId());
		logger.info("retrieve card is " + card);
		return ActionStateConstants.SUCCESS;
	}

	@Override
	public String update() throws Exception {
		logger.info(card.getId() + "CardAction update() card is " + card);
		userId = ((User) getSession().get(SESSION_USER)).getId();
		card.setUser(userService.retrieveEntity(userId));
		logger.info("Whole Card object is " + card);
		cardService.updateEntity(card);

		logger.info("CardAction update() success!!! userId=" + userId);
		return ActionStateConstants.SUCCESS;
	}

	@Override
	public void validate() {

		if (card.getCardNumber() == null || card.getCardNumber().equals("")) {
			addFieldError("cardnumber", "cardnumber can not null");
		}

	}

	public Card getModel() {
		return card;
	}

	public Integer getUserId() {
		return userId;
	}

	public void setUserId(Integer userId) {
		this.userId = userId;
	}

	public Card getCard() {
		return card;
	}

	public void prepare() throws Exception {
		// TODO Auto-generated method stub
		
	}

}
